from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from .models import Results, ResultQuestionSolution
from ..PaperManagement.models import PaperQuestion


class ResultsSerializer(serializers.ModelSerializer):
    """答题卡列表序列化器"""
    exam_title = serializers.CharField(source='exam.title', read_only=True)
    user_name = serializers.CharField(source='user.name', read_only=True)
    department_name = serializers.CharField(source='user.depart.name', read_only=True)
    total_score = serializers.IntegerField(default=0)

    class Meta:
        model = Results
        fields = ["id", "exam_title", "user_name", "total_score", "department_name"]


class ResultQuestionSolutionSerializer(serializers.ModelSerializer):
    questionsInfo = serializers.SerializerMethodField()

    class Meta:
        model = ResultQuestionSolution
        fields = ["id", "solution", "score", "created_at", "updated_at", "questionsInfo"]

    def get_questionsInfo(self, obj):
        question = obj.question
        paper = obj.results.exam.paper if obj.results.exam and obj.results.exam.paper else None

        # 返回试题信息
        question_info = {
            "id": str(question.id),
            "topic": question.topic,
            "score": self.get_question_score(paper, question),
            "type": question.type
        }

        # 根据题目类型返回答案或关键词
        if question.type == "short":
            question_info["keywords"] = question.keywords
        else:
            question_info["options"] = question.options
            question_info["answer"] = question.answer

        return question_info

    def get_question_score(self, paper, question):
        """根据试卷ID和试题ID查询试题的得分"""
        if paper:
            try:
                paper_question = PaperQuestion.objects.get(paper=paper, question=question)
                return paper_question.score  # 返回试题的得分
            except ObjectDoesNotExist:
                return 0  # 如果没有找到该试题与试卷的关联，返回0分
        return 0  # 如果没有试卷ID，返回0分


class ResultDetailSerializer(serializers.ModelSerializer):
    exam_title = serializers.CharField(source='exam.title', read_only=True)
    user_name = serializers.CharField(source='user.name', read_only=True)
    department_name = serializers.CharField(source='user.depart.name', read_only=True)
    paper_total_score = serializers.IntegerField(source='exam.paper.total_score', read_only=True)
    total_score = serializers.IntegerField(read_only=True)
    card = serializers.SerializerMethodField()

    class Meta:
        model = Results
        fields = ["id", "exam_title", "user_name", "department_name", "paper_total_score", "total_score", "card"]

    def get_card(self, obj):
        result_question_solutions = ResultQuestionSolution.objects.filter(results=obj)

        if not result_question_solutions:
            return []

        # 使用 ResultQuestionSolutionSerializer 对每个实例进行序列化
        serializer = ResultQuestionSolutionSerializer(result_question_solutions, many=True)
        return serializer.data
